<template>
  <div>
    <a-button type="primary" @click="show = true">批量计划&单元</a-button>
    <a-modal v-model="show" :width="600" okText="提交" @ok="ok" :confirm-loading="fuzhiLoading">
      <a-form-model ref="ruleForm" :model="bulkForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="名称前缀" prop="customCampaignName">
          <a-input v-model="bulkForm.customCampaignName"/>
        </a-form-model-item>
        <a-form-model-item label="类型" prop="ideaTypes">
          <a-checkbox-group v-model="bulkForm.ideaTypes" @change="ontypeCheckChange">
            <a-row style="margin-top:9px;">
              <a-col :span="12">
                <a-checkbox :value="1">自定义</a-checkbox>
              </a-col>
              <a-col :span="12">
                <a-checkbox :value="2">程序化</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-model-item>
        <a-form-model-item label="投放场景" prop="campaignType">
          <a-radio-group v-model="bulkForm.campaignType" button-style="solid">
            <a-radio-button :value="1">普通模式</a-radio-button>
            <a-radio-button :value="4">放量模式</a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="预算" prop="budget" v-if="bulkForm.campaignType == 4">
          <a-input-number addon-after="元/天" v-model="bulkForm.budget" :min="50"/> 元/天
        </a-form-model-item>
        <a-form-model-item label="基木鱼页面" prop="jmyPageUrl">
          <a-select v-model="bulkForm.jmyPageUrl" show-search optionFilterProp="pageName" :filter-option="jmyfilterOption">
            <a-select-option :value="item.onlineUrl" v-for="(item,index) in jmyOptions" :key="index" >
              {{item.pageName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="单元模板" prop="sourceTplAdgroupIds">
          <a-select v-model="bulkForm.sourceTplAdgroupIds" mode="multiple" show-search optionFilterProp="adgroupFeedName" :filter-option="jmyfilterOption">
            <div slot="dropdownRender" slot-scope="menu">
              <!-- 自定义select下拉 制作全选功能 -->
              <div style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()" @click="selectMubanAll" >
                <a-icon type="plus" /> {{selectAllStatus==0?'全选':'取消选择'}}
              </div>
              <a-divider style="margin: 4px 0;" />
              <v-nodes :vnodes="menu" />
            </div>
            <a-select-option :value="item.adgroupFeedId" v-for="(item,index) in tplOptions" :key="index" >
              {{item.adgroupFeedName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="价格区间">
          <div style="display:flex;align-items:center;">
            <a-input-number v-model="bulkForm.start_price" :min="0" />
            <div style="padding:0 10px;">-</div>
            <a-input-number v-model="bulkForm.end_price" :min="0" />
          </div>
        </a-form-model-item>
        <a-form-model-item label="目标账户" prop="destAccountIds">
          <a-select v-model="bulkForm.destAccountIds" mode="multiple" show-search optionFilterProp="account" :filter-option="jmyfilterOption">
            <a-select-option :value="item.id" v-for="(item,index) in accountList" :key="index" >
              {{item.account}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
      <template slot="title" >
        <span style="display:flex;align-items: center;">
          批量基木鱼
          <a-tooltip style="margin-left:6px;">
            <template slot="title">
              异步提交：会将任务放到后台执行，减少页面等待时间
            </template>
            <a-icon style="cursor: pointer;" type="exclamation-circle" :style="{ fontSize: '12px',color:'#888888' }"/>
          </a-tooltip>
        </span>
      </template>
      <template slot="footer">
        <a-button @click="show = false">取消</a-button>
        <a-button type="primary" :loading="fuzhiLoading" @click="ok">提交</a-button>
        <a-button type="primary" :loading="fuzhiLoading" @click="asyncOk">异步提交</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { getJmyPromotionPage,getTplAdgroupFeed,createFromTpl,asyncCreateFromTpl } from '@/api/xinxiliu/getBaidu'
import { getBdAccountList } from '@/api/xinxiliu/account'

export default {
  name:'bulkJHDY',
  data(){
    return{
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      show: false,
      fuzhiLoading: false,
      bulkForm:{
        customCampaignName:'',
        ideaTypes:[1],
        jmyPageUrl:'',
        sourceTplAdgroupIds:[],
        start_price: 0,
        end_price: 0,
        destAccountIds:[],
        campaignType:1,
        budget:200,
      },
      rules:{
        customCampaignName: [{required: true, message: '请输入名称前缀', trigger: 'blur' }],
        ideaTypes: [{required: true, message: '类型不能为空', trigger: 'blur' }],
        jmyPageUrl: [{required: true, message: '请选择基木鱼页面', trigger: 'blur' }],
        sourceTplAdgroupIds: [{required: true, message: '请选择单元模板', trigger: 'blur' }],
        destAccountIds: [{required: true, message: '请选目标账户', trigger: 'blur' }],
        campaignType: [{required: true, message: '请选投放场景', trigger: 'blur' }],
      },
      jmyOptions:[],
      tplOptions:[],
      accountList:[],

      copy_ideaTypes:[1],

      selectAllStatus: 0,
    }
  },
  methods:{
    init(){
      this.getBdAccountList()
    },
    getBdAccountList(){
      getBdAccountList({}).then((res) => {
        if(res.errcode == 0){
          if(this.bulkForm.destAccountIds.length == 0){
            this.bulkForm.destAccountIds.push(this.$store.state.dianpu.id)
          }
          this.accountList = res.data
        }
        this.getJmyPromotionPage()
        this.getTplAdgroupFeed()
      })
    },
    getJmyPromotionPage(){
      getJmyPromotionPage({}).then((res) => {
        if(res.errcode == 0){
          this.jmyOptions = res.data.body.data[0].pageList
        }
      });
    },
    getTplAdgroupFeed(){
      getTplAdgroupFeed({}).then((res) => {
        if(res.errcode == 0){
          this.tplOptions = res.data
        }
      });
    },
    ok(){
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let bulkForm = JSON.parse(JSON.stringify(this.bulkForm))
          bulkForm.ideaTypes = bulkForm.ideaTypes.join(',')
          bulkForm.sourceTplAdgroupIds = bulkForm.sourceTplAdgroupIds.join(',')
          bulkForm.destAccountIds = bulkForm.destAccountIds.join(',')
          if(bulkForm.campaignType == 1){
            delete bulkForm.budget
          }
          // console.log(bulkForm,createFromTpl)
          this.fuzhiLoading = true
          createFromTpl(bulkForm).then((res) => {
            this.fuzhiLoading = false
            console.log(res)
            if(res.errcode == 0){
              this.$message.success('创建成功')
              this.show = false
              this.$emit('confirm')
            }
          }).catch(() => {
            this.fuzhiLoading = false
          });
        } 
      })
    },
    asyncOk(){
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let bulkForm = JSON.parse(JSON.stringify(this.bulkForm))
          bulkForm.ideaTypes = bulkForm.ideaTypes.join(',')
          bulkForm.sourceTplAdgroupIds = bulkForm.sourceTplAdgroupIds.join(',')
          bulkForm.destAccountIds = bulkForm.destAccountIds.join(',')
          if(bulkForm.campaignType == 1){
            delete bulkForm.budget
          }
          this.fuzhiLoading = true
          asyncCreateFromTpl(bulkForm).then((res) => {
            this.fuzhiLoading = false
            if(res.errcode == 0){
              this.$message.success(res.errmsg)
              this.show = false
              // this.$emit('confirm')
            }
          }).catch(() => {
            this.fuzhiLoading = false
          });
        } 
      })
    },
    selectMubanAll(){
      // 单元模板全选
      let arr = []
      if(this.selectAllStatus == 0){
        this.tplOptions.forEach(e => {
          arr.push(e.adgroupFeedId)
        });
        this.selectAllStatus = 1
      }else{
        this.selectAllStatus = 0
      }
      this.bulkForm.sourceTplAdgroupIds = arr
    },
    jmyfilterOption(input, option){
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    ontypeCheckChange(e){
      if(e.length == 0){
        this.$message.error('必须选择一项')
        this.bulkForm.ideaTypes = JSON.parse(JSON.stringify(this.copy_ideaTypes))
      }
    }
  },
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  watch:{
    'show'(e){
      if(e){
        this.init()
      }
    },
    'bulkForm.ideaTypes'(e){
      this.copy_ideaTypes = JSON.parse(JSON.stringify(e))
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-select-selection--multiple{
  max-height: 140px;
  overflow-y: auto;
}
</style>